# -*- encoding: utf-8 -*-
'''
@文件    :   wx.py
@时间    :   2021/05/07 15:11:40
@作者  :   Thinktank
@版本 :   1.0
@简介 :   
@许可 :   
@描述    :   None
'''

# 这里放 import lib

import sys

# sys.path.append(r'F:\ftproot\Projects\2021\luoyunoa')
# import luoyunoa
import configparser
import os
import random
import threading
import time
import tkinter
import webbrowser
from TkinterDnD2 import *
from tkinter import messagebox
from tkinter import simpledialog
import baiduocr
import getsq
import mysql
import win2test
from PIL import Image, ImageTk, ImageGrab
from wxpy import *

from swpng import getswpng

os.system('title 微信助手')
local_path = os.path.abspath(os.curdir)
ID_list = [
    '9789b39bf27b4f338820f1fa6eef84e7', 'ec4ccb4a8af049ceb1a6517506f14e6f',
    '746369696c4b4cf09d1a652aa845c94c', '121f7ca1797644b0b6a1a2e45b03b604'
]


def getnowtime():
    return str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))


# 获取键盘输入值
def getkey(evt):
    # print(evt.char)
    # print(evt.keycode)
    if evt.keycode == 13:
        # messagebox.showinfo("提示", "Ctr+回车")
        sndbtnclick()


class Globaldata:
    oa_running = False
    oa_isalive = False


bot = None
my_self = None


# 登陆
def login():
    global bot
    global my_self
    bot = Bot(cache_path=True)
    print(bot)
    my_self = bot.self
    my_self.get_avatar(r"avatar\self.jpg")
    tempfilepager = r"avatar\self.jpg"
    tmppil_img = Image.open(tempfilepager)
    tmppil_img = tmppil_img.resize((50, 50), Image.ANTIALIAS)
    tmptk_img = ImageTk.PhotoImage(tmppil_img)
    botimg.config(image=tmptk_img)
    botimg.image = tmptk_img
    titlevar.set(my_self)
    bot.enable_puid('wxpy_puid.pkl')
    # Bot.auto_mark_as_read = True
    print("登陆成功")
    lbltitle["bg"] = "green"
    refreshbtn["state"] = tkinter.NORMAL
    sndbtn["state"] = tkinter.NORMAL
    getfrndbtn["state"] = tkinter.NORMAL
    if autoallfrnds == 1:
        getfrndbtnclick()
    if autogroups == 1:
        refreshbtnclick()
        # 监听所有好友信息

    @bot.register(chats=[Friend], except_self=False)
    def just_get(msg):
        # 获取发送者信息名称
        sender = msg.chat.name
        if not isexistinfrndlst(sender):
            frndlst.insert(tkinter.END, sender)
        print(getnowtime() + '[接收]' + str(msg))
        rcvlst.insert(0, getnowtime() + '[接收]' + str(msg))
        sender_path = "data\\friends\\" + sender + "\\" + msg.type
        isexists = os.path.exists(sender_path)
        if not isexists:
            os.makedirs(sender_path)
        with open("data\\friends\\" + sender + "\\message.txt", "a+") as f1:
            f1.write(getnowtime() + '[接收]' + str(msg) + "\n")
        rndstr = str(random.randint(1000, 2000))
        if msg.file_name:
            filepath = sender_path + "\\" + rndstr + msg.file_name
        else:
            filepath = "无路径"
        # 发送者为自己
        if sender == my_self.name:
            if msg.text == "1":
                print(getnowtime() + "收到刷新指令，开始刷新群信息")
                bot.file_helper.send(getnowtime() + "收到刷新指令，开始刷新群信息")
                msgsendtorefesh()
            if msg.text == "2":
                print(getnowtime() + "收到截屏指令，开始截屏")
                bot.file_helper.send(getnowtime() + "收到截屏指令，开始截屏")
                printscreen()
        else:
            if msg.type == "Sharing":
                print(msg.url)
                filepath = msg.url
                rcvlst.insert(0, getnowtime() + msg.type + '[链接为→]' + filepath)
                with open(sender_path + "\\message.txt", "a+") as f1:
                    f1.write(getnowtime() + msg.type + '[链接为→]' + filepath +
                             "\n")
            elif msg.type != 'Text' and msg.type != 'Note':
                print(getnowtime() + msg.type + '[保存到→]' + filepath)
                msg.get_file(filepath)
                rcvlst.insert(0, getnowtime() + msg.type + '[保存到→]' + filepath)
                with open(sender_path + "\\message.txt", "a+") as f1:
                    f1.write(getnowtime() + msg.type + '[保存到→]' + filepath +
                             "\n")
        # (mname, chatt, chatc, chatp, chatgs):
        try:
            msg_text = msg.text
        except:
            msg_text = msg.type
        mysql.insertdata(sender, getnowtime(), msg_text, msg.type,
                         "private_to_me", filepath)


def loginth():
    titlevar.set("正在登陆，若长时间未获得账号，请查看手机是否需要授权或检查网络")
    th = threading.Thread(target=login)
    th.setDaemon(True)
    th.start()


def logout():
    Bot.logout(bot)
    titlevar.set("未登陆")
    lbltitle["bg"] = "red"
    tmpfilename = r"avatar\logout.jpg"
    tmppil_img = Image.open(tmpfilename)
    tmppil_img = tmppil_img.resize((50, 50), Image.ANTIALIAS)
    tmptk_img = ImageTk.PhotoImage(tmppil_img)
    botimg.config(image=tmptk_img)
    botimg.image = tmptk_img
    sndvar.set("未知目标")
    sndlbl["fg"] = "red"
    sndimg.config(image=tmptk_img)
    sndimg.image = tmptk_img
    sndbtn["state"] = tkinter.DISABLED
    refreshbtn["state"] = tkinter.DISABLED
    getfrndbtn["state"] = "disabled"
    # botimg.pack(side=tkinter.LEFT)
    # lbltitle = tkinter.Label(framemain, textvariable=titlevar, bg="red", fg="white", font=("微软雅黑", 10))


def changeuser():
    try:
        os.remove("wxpy.pkl")
        print("删除成功")
    except:
        print("不存在该文件")
    finally:
        loginth()


def isexistinfrndlst(frndname):
    isexist = False
    # print(frndname)
    # print(frndlst.get(0, 'end'))
    try:
        for frnd in frndlst.get(0, 'end'):
            # print(frnd)
            # print(type(frnd))
            if frndname == frnd:
                isexist = True
                break
    except:
        isexist = False
    finally:
        return isexist


def msgsavetotxt(msg):
    with open(r'data\msg.txt', 'a+') as f:
        f.write(msg + '\n')
    print('消息保存')


def textreadln(text):
    tmparray = []
    tmpstr = ""
    for i in text.get(0., "end"):
        if i != "\n":
            tmpstr += i
        elif tmpstr != "":
            tmparray.append(tmpstr)
            tmpstr = ""
    return tmparray


search_groups = []


def refreshgroups():
    refreshbtn['state'] = tkinter.DISABLED
    try:
        global search_groups
        global bot
        global my_self
        search_groups = []
        rstlst.delete(0, tkinter.END)
        with open('config\\groups.txt', 'r') as f:
            for line in f:
                # print(line.replace('\n', ''))
                my_groups_name = line.replace('\n', '')
                search_groups.append(my_groups_name)
        # 是否更新，是否保存为联系人
        all_groups = bot.groups(update=True, contact_only=False)
        print(all_groups)
        print(search_groups)
        target_group = bot.groups().search('测试2群')[0]
        # log_group = bot.groups().search('测试3群')[0]
        print(target_group)
        for group in search_groups:
            mgroups = all_groups.search(group)
            if len(mgroups) != 0:
                print(mgroups)
                print("监听中")

                for mgroup in mgroups:
                    rstlst.insert(tkinter.END, mgroup.name)

                @bot.register(mgroups, except_self=False)
                def group_message(msg):
                    print(getnowtime() + str(msg))
                    rndstr = str(random.randint(1000, 2000))
                    rcvlst.insert(0, getnowtime() + '[接收]' + str(msg))
                    msg_type = msg.type
                    # 发送来自的群名称
                    msg_group_name = msg.chat.name
                    msg_member_name = msg.member.name.replace(" ", "")
                    key_name = ['老师', '班主任', '請迴答', '科学', '白开水']
                    if any(key in msg_member_name for key in key_name):
                        print(bot.groups().search('一家三口'))
                        msg.forward(bot.groups().search('一家三口')[0],
                                    prefix=msg_member_name)
                    msg_path = "data\\groups\\" + msg_group_name + \
                        "\\" + msg_member_name + "\\" + msg_type + "\\"
                    isexists = os.path.exists(msg_path)
                    if not isexists:
                        os.makedirs(msg_path)
                    global my_self
                    my_name = my_self.name
                    with open(
                            "data\\groups\\" + msg_group_name +
                            "\\message.txt", "a+") as f2:
                        if msg_member_name == my_name:
                            f2.write(getnowtime() + '[接收]' +
                                     str(msg).replace("↪", "→") + "\n")
                        else:
                            f2.write(getnowtime() + '[接收]' +
                                     str(msg).replace("›", "→") + "\n")

                    filepath = "无路径"
                    if msg.type != 'Text':
                        if msg.type == "Sharing":
                            filepath = msg.url
                            rcvlst.insert(
                                0,
                                getnowtime() + msg.type + '[链接为→]' + filepath)
                        else:
                            filename = msg_member_name + rndstr + \
                                msg.file_name.replace(" ", "")
                            filepath = msg_path + filename
                            msg.get_file(filepath)
                            print(msg_type + "[保存到→]" + filepath)
                            rcvlst.insert(
                                0,
                                getnowtime() + msg_type + "[保存到→]" + filepath)
                    if msg_group_name.find("测试2群") >= 0:
                        if msg.type == "Picture":  # and my_name.lower() == 'thinktank':
                            msg.reply("已收到" + msg_member_name +
                                      "的图片，正在转换，请稍后。。。")
                            txtfile = 'data\\pictotxt\\' + msg_member_name + "\\" + filename + '.txt'
                            if not os.path.exists(os.path.dirname(txtfile)):
                                os.makedirs(os.path.dirname(txtfile))
                            pictotxt = baiduocr.pictotxt2(filepath)
                            with open(txtfile, "w") as tf:
                                for txt in pictotxt["words_result"]:
                                    print(txt["words"])
                                    tf.write(txt["words"] + '\n')
                            msg.reply_file(txtfile)
                            rcvlst.insert(
                                0,
                                getnowtime() + "识别已发送[保存到→]" + txtfile)
                        if msg.type == "Text":
                            if msg.text.find("水位") >= 0:
                                sq = getsq.getsq("刘老涧", "", "")
                                print(sq)
                                msg.reply(sq)
                                try:
                                    getswpng(ID_list=ID_list)
                                    for _id in ID_list:
                                        msg.reply_image(
                                            f"{local_path}{os.sep}data{os.sep}{_id}.png"
                                        )
                                except Exception as e:
                                    print(e)
                            elif msg.text.find("一站") >= 0:
                                gq = getsq.getgq_1zhan()
                                msg.reply(gq)
                            elif msg.text.find("二站") >= 0:
                                msg.reply("尚未开发，敬请期待") 
                    try:
                        msg_text = msg.text
                    except:
                        msg_text = msg.type
                    mysql.insertdata(msg_member_name, getnowtime(), msg_text,
                                     msg.type, msg_group_name, filepath)

        print(getnowtime() + "更新完成")

    except Exception as e:
        print(getnowtime() + "更新发生错误")
        print("错误信息：", e)
    finally:
        refreshbtn['state'] = tkinter.NORMAL
    return


def getscreenshot():
    imgshot = ImageGrab.grab()
    imgshot.save(r"screenshot\now.png")


# 直接点击刷新
def refreshbtnclick():
    th = threading.Thread(target=refreshgroups)
    th.setDaemon(True)
    th.start()
    return


# 微信发送刷新
def msgsendtorefesh():
    th = threading.Thread(target=refreshgroups)
    th.setDaemon(True)
    th.start()
    bot.file_helper.send(getnowtime() + "更新完成")
    return


# 截屏
def printscreen():
    th = threading.Thread(target=getscreenshot)
    th.setDaemon(True)
    th.start()
    time.sleep(5)
    bot.file_helper.send_image("screenshot\\now.png")

    return


# “自动登陆”check值
def changeautologin():
    global config
    config.set("auto", "autologin", var1.get())
    config.write(open('config\\config.ini', "r+"))


# “自动载入群”check值
def changeautogroups():
    global config
    config.set("auto", "autogroups", var2.get())
    config.write(open('config\\config.ini', "r+"))


def changeautofrnds():
    global config
    config.set("auto", "autoallfriends", var3.get())
    config.write(open('config\\config.ini', "r+"))


# 开始菜单点击
def m1click():
    tmpstr = ""
    i = 0
    with open('config\\groups.txt', 'r') as f:
        for line in f:
            i += 1
            tmpstr += r"    " + str(i) + '、' + line
            # tmpstr.append(line.replace('\n', ''))
        print(tmpstr)
        if messagebox.askokcancel("提示",
                                  "监听群列表：\n\n" + str(tmpstr) + "\n\n要编辑操作吗？"):
            os.system("notepad config\\groups.txt")
    return


targetfrnd = ""


# 双击群列表
def rstlstdbclick(evt):
    global targetfrnd
    if rstlst.size() > 0:
        lstvalue = rstlst.get(rstlst.curselection())
        targetfrnd = bot.groups().search(lstvalue)[0]
        print("发送目标为：")
        print(targetfrnd)
        sndvar.set(targetfrnd.name)
        sndlbl["fg"] = "blue"
        apath = "avatar\\" + targetfrnd.name + ".jpg"
        if not os.path.exists(apath):
            targetfrnd.get_avatar("avatar\\" + targetfrnd.name + ".jpg")
        tmpimg = Image.open(apath)
        tmpimg = tmpimg.resize((50, 50), Image.ANTIALIAS)
        tmptk = ImageTk.PhotoImage(tmpimg)
        sndimg.config(image=tmptk)
        sndimg.image = tmptk


# 最近联系列表双击
def frndlstdbclick(evt):
    global targetfrnd
    # print(frndlst.size())
    if frndlst.size() != 0:
        lstvalue = frndlst.get(frndlst.curselection())
        # targetfrnd = bot.friends().search(lstvalue)[0]
        # 唯一名称获取
        targetfrnd = ensure_one(bot.friends().search(lstvalue))
        print("发送目标为：")
        print(targetfrnd)
        sndvar.set(targetfrnd.name)
        sndlbl["fg"] = "blue"
        apath = "avatar\\" + targetfrnd.name + ".jpg"
        if not os.path.exists(apath):
            targetfrnd.get_avatar("avatar\\" + targetfrnd.name + ".jpg")
        tmpimg = Image.open(apath)
        tmpimg = tmpimg.resize((50, 50), Image.ANTIALIAS)
        tmptk = ImageTk.PhotoImage(tmpimg)
        sndimg.config(image=tmptk)
        sndimg.image = tmptk
        # targetfrnd.send("你好")


# 全部好友
def allfrndlstdbclick(evt):
    global targetfrnd
    print(allfrndlst.size())
    if allfrndlst.size() != 0:
        lstvalue = allfrndlst.get(allfrndlst.curselection())
        # targetfrnd = bot.friends().search(lstvalue)[0]
        # 唯一名称获取
        targetfrnd = ensure_one(bot.friends().search(lstvalue))
        print("发送目标为：")
        print(targetfrnd)
        sndvar.set(targetfrnd.name)
        sndlbl["fg"] = "blue"
        apath = "avatar\\" + targetfrnd.name + ".jpg"
        if not os.path.exists(apath):
            targetfrnd.get_avatar("avatar\\" + targetfrnd.name + ".jpg")
        tmpimg = Image.open(apath)
        tmpimg = tmpimg.resize((50, 50), Image.ANTIALIAS)
        tmptk = ImageTk.PhotoImage(tmpimg)
        sndimg.config(image=tmptk)
        sndimg.image = tmptk
        # targetfrnd.send("你好")


# 右键搜索好友
def srchfrndclick(evt):
    srchfrnd = simpledialog.askstring(title='查找好友', prompt='输入好友名称')
    if srchfrnd != "":
        print(srchfrnd)
        global targetfrnd
        # 唯一名称获取
        targetfrnd = ensure_one(bot.friends().search(srchfrnd))
        print("发送目标为：")
        print(targetfrnd)
        sndvar.set(targetfrnd.name)
        sndlbl["fg"] = "blue"
        apath = "avatar\\" + targetfrnd.name + ".jpg"
        if not os.path.exists(apath):
            targetfrnd.get_avatar("avatar\\" + targetfrnd.name + ".jpg")
        tmpimg = Image.open(apath)
        tmpimg = tmpimg.resize((50, 50), Image.ANTIALIAS)
        tmptk = ImageTk.PhotoImage(tmpimg)
        sndimg.config(image=tmptk)
        sndimg.image = tmptk


def getfrndbtnclick():
    allfrndlst.delete(0, "end")
    print(bot.friends(update=True))
    for user_friend in bot.friends():
        print(user_friend.name)
        allfrndlst.insert(tkinter.END, user_friend.name)


# 双击接收消息列表
def rcvlstdbclick(evt):
    if rcvlst.size() > 0:
        rcvvalue = rcvlst_getitem()
        find = rcvvalue.find("保存到→]")
        if find >= 0:
            rcvpath = os.getcwd() + "\\" + rcvvalue[find + 5:]
            # rcvpath.replace(r"/", r"\\")
            print(rcvpath)
            os.system(rcvpath)
        find = rcvvalue.find("链接为→]")
        if find >= 0:
            rcvpath = rcvvalue[find + 5:]
            print(rcvpath)
            webbrowser.open(rcvpath)


# 右键接收消息列表
def rcvlstrightclick(evt):
    # print(rcvlst_getitem())
    global dir_path
    dir_path = rcvlst_getitem()
    start = dir_path.find("[保存到→]")
    if start > 0:
        start += len("[保存到→]")
        dir_path = dir_path[start:]
        menu_pop.post(evt.x_root, evt.y_root)
        # print(dir_path)
        # return


# 获取rcvlst选择的值
def rcvlst_getitem():
    if rcvlst.curselection():
        return str(rcvlst.get(rcvlst.curselection()))
    else:
        return ""


# 打开目录
def rcvlst_opendir():
    # os.system("start explorer c:")  # c:为要打开c盘，也可以改成其他路径
    global dir_path
    dir_path = os.path.dirname(os.getcwd() + '\\' +
                               dir_path.replace("\\\\", "\\"))
    dir_path = "start explorer " + dir_path
    # print(dir_path)
    os.system(dir_path)


# 判断是否为图片
def is_img(ext):
    ext = ext.lower()
    if ext == 'jpg':
        return True
    elif ext == 'png':
        return True
    elif ext == 'jpeg':
        return True
    elif ext == 'bmp':
        return True
    elif ext == 'gif':
        return True
    else:
        return False


# 判断是否是视频
def is_video(ext):
    ext = ext.lower()
    if ext == 'mp4':
        return True
    elif ext == 'mov':
        return True
    else:
        return False


# 点击发送信息给目标
def sndmsg():
    sndbtn["state"] = tkinter.DISABLED
    global targetfrnd
    print(targetfrnd)
    try:
        if targetfrnd:
            sndarray = textreadln(sndtext)
            # print(sndarray)
            if len(sndarray) > 0:
                for readln in sndarray:
                    # print(readln)
                    if readln.find("^") >= 0:
                        readln = readln[readln.find("^") + 1:]
                        tmp = readln.split(".")
                        tmp = tmp[len(tmp) - 1]
                        if is_img(tmp):
                            print("发送图片")
                            # sent_msgs = targetfrnd.send_image(readln)
                            sent_msgs = targetfrnd.send("@img@" + readln)
                            print(readln)
                        elif is_video(tmp):
                            print("发送视频")
                            # sent_msgs = targetfrnd.send_video(readln)
                            sent_msgs = targetfrnd.send("@vid@" + readln)
                            print(readln)
                        else:
                            print("发送文件")
                            # sent_msgs = targetfrnd.send_file(readln)
                            sent_msgs = targetfrnd.send("@fil@" + readln)
                            print(readln)
                    elif len(readln) > 0:
                        print("发送文字")
                        sent_msgs = targetfrnd.send(readln)
                    rcvlst.insert(0, getnowtime() + "[发送]" + str(sent_msgs))
                    print(sent_msgs)
            sndtext.delete(0., "end")
        else:
            messagebox.showwarning("错误", "未选中聊天对象")
    except:
        print("发送错误")
    finally:
        sndbtn["state"] = tkinter.NORMAL


# 多线程点击发送信息给目标
def sndbtnclick():
    th = threading.Thread(target=sndmsg)
    th.setDaemon(True)
    th.start()


# 拖动文件获取路径
def drop(event):
    if event.data:
        # print('Dropped data:\n', event.data)
        files = sndtext.tk.splitlist(event.data)
        for f in files:
            if os.path.exists(f):
                print('拖入文件: "%s"' % f)
                sndtext.insert('end', "^" + f + '\n')
            else:
                print('拖入文件无效 "%s": 不存在。' % f)
    return event.action


def rootexit():
    if messagebox.askyesno("提示", "确定退出？"):
        sys.exit(0)


if __name__ == "__main__":
    canDrop = False
    try:
        root = TkinterDnD.Tk()
        canDrop = True
    except:
        root = tkinter.Toplevel()
    root.resizable(width=True, height=False)
    root.geometry("800x600")
    titlevar = tkinter.StringVar()
    titlevar.set("未登陆")
    root.title("微信助手")
    # 读取config设置
    config = configparser.ConfigParser()
    config.read(r'config\config.ini')
    autologin = int(config.get("auto", "autologin"))
    autogroups = int(config.get("auto", "autogroups"))
    autoallfrnds = int(config.get("auto", "autoallfriends"))
    # 主菜单
    menubar = tkinter.Menu(root)
    menu_1 = tkinter.Menu(menubar, tearoff=0)
    menubar.add_cascade(label='账号', menu=menu_1)
    menu_1.add_command(label='登陆', command=loginth)
    menu_1.add_command(label='登出', command=logout)
    menu_1.add_separator()
    menu_1.add_command(label="切换账号", command=changeuser)
    menu_1.add_command(label='退出', command=rootexit)
    menu_2 = tkinter.Menu(menubar, tearoff=0)
    menubar.add_cascade(label='设置', menu=menu_2)
    menu_2.add_command(label='查看/修改监听群', command=m1click)
    menu_2.add_separator()
    var1 = tkinter.StringVar()
    menu_2.add_checkbutton(label="自动登陆",
                           variable=var1,
                           onvalue=1,
                           offvalue=0,
                           command=changeautologin)
    var1.set(autologin)
    var2 = tkinter.StringVar()
    var2.set(autogroups)
    menu_2.add_checkbutton(label="自动监听所选群",
                           variable=var2,
                           onvalue=1,
                           offvalue=0,
                           command=changeautogroups)
    var3 = tkinter.StringVar()
    var3.set(autoallfrnds)
    menu_2.add_checkbutton(label="自动导入好友",
                           variable=var3,
                           onvalue=1,
                           offvalue=0,
                           command=changeautofrnds)
    # menu_2.add_checkbutton(label="监听好友信息")
    menu_3 = tkinter.Menu(menubar, tearoff=0)
    menubar.add_cascade(label='关于', menu=menu_3)
    menu_3.add_command(label='版本信息')
    menu_3.add_command(label='新窗口', command=win2test.showwxdbwin)
    root['menu'] = menubar
    # 顶部标题栏
    framemain = tkinter.Frame(root)
    filename1 = r"avatar\logout.jpg"
    img_bot = Image.open(filename1)
    img_bot = img_bot.resize((50, 50), Image.ANTIALIAS)
    tk_bot = ImageTk.PhotoImage(img_bot)
    botimg = tkinter.Label(framemain, width=30, height=30)
    botimg.pack(side=tkinter.LEFT)
    botimg.config(image=tk_bot)
    botimg.image = tk_bot
    lbltitle = tkinter.Label(framemain,
                             textvariable=titlevar,
                             bg="red",
                             fg="white",
                             font=("微软雅黑", 10))
    lbltitle.pack(side=tkinter.LEFT, fill=tkinter.BOTH)
    framemain.pack(side=tkinter.TOP, fill=tkinter.BOTH)

    framelbl = tkinter.Frame(root)
    lbl1 = tkinter.Label(framelbl, text='监听群列表', width=32)
    lbl1.pack(side=tkinter.LEFT)
    lbl2 = tkinter.Label(framelbl, text='最近联系人', width=20)
    lbl2.pack(side=tkinter.LEFT)
    lbl3 = tkinter.Label(framelbl, text='信息内容', width=20)
    lbl3.pack()
    # lbl4 = tkinter.Label(framelbl, text='信息内容')
    # lbl4.pack(fill=tkinter.BOTH)
    framelbl.pack(side=tkinter.TOP, fill=tkinter.BOTH)
    frame1 = tkinter.Frame(root)
    frame12 = tkinter.Frame(frame1)
    refreshbtn = tkinter.Button(frame12,
                                text='群导入',
                                width=15,
                                bg="green",
                                fg="white",
                                command=refreshbtnclick)
    refreshbtn.pack(side=tkinter.BOTTOM)
    refreshbtn["state"] = tkinter.DISABLED

    # 筛选群结果
    scrollbar1 = tkinter.Scrollbar(frame12)
    scrollbar1.pack(side=tkinter.RIGHT, fill=tkinter.Y)
    rstlst = tkinter.Listbox(frame12,
                             width=30,
                             height=30,
                             yscrollcommand=scrollbar1.set)
    scrollbar1.config(command=rstlst.yview)
    rstlst.pack(fill=tkinter.BOTH)
    rstlst.bind("<Double-Button-1>", func=rstlstdbclick)
    frame12.pack(side=tkinter.LEFT, fill=tkinter.BOTH)

    # 联系人名单
    frame13 = tkinter.Frame(frame1)
    frame131 = tkinter.Frame(frame13)
    scrollbar2 = tkinter.Scrollbar(frame131)
    scrollbar2.pack(side=tkinter.RIGHT, fill=tkinter.Y)
    frndlst = tkinter.Listbox(frame131,
                              width=20,
                              yscrollcommand=scrollbar2.set)
    scrollbar2.config(command=frndlst.yview)
    frndlst.pack(side=tkinter.TOP, fill=tkinter.Y)
    frndlst.bind('<Double-Button-1>', func=frndlstdbclick)
    frame131.pack()
    frame132 = tkinter.Frame(frame13)
    lbl4 = tkinter.Label(frame132, text="全部好友")
    lbl4.pack()
    scrollbar3 = tkinter.Scrollbar(frame132)
    scrollbar3.pack(side=tkinter.RIGHT, fill=tkinter.Y)
    allfrndlst = tkinter.Listbox(frame132,
                                 height=19,
                                 yscrollcommand=scrollbar3.set)
    scrollbar3.config(command=allfrndlst.yview)
    allfrndlst.pack(side=tkinter.TOP, fill=tkinter.BOTH)
    allfrndlst.bind("<Double-Button-1>", func=allfrndlstdbclick)
    allfrndlst.bind("<Button-3>", func=srchfrndclick)
    getfrndbtn = tkinter.Button(frame13,
                                text="获取全部好友",
                                bg="green",
                                fg="white",
                                command=getfrndbtnclick)
    getfrndbtn.pack(side=tkinter.BOTTOM)
    getfrndbtn["state"] = tkinter.DISABLED
    frame132.pack(side=tkinter.TOP, fill=tkinter.BOTH)
    frame13.pack(side=tkinter.LEFT, fill=tkinter.BOTH)

    frame1.pack(side=tkinter.LEFT, fill=tkinter.BOTH)

    frame2 = tkinter.Frame(root)

    # 接收信息清单
    frame21 = tkinter.Frame(frame2)
    scrollbar4 = tkinter.Scrollbar(frame21)
    scrollbar4.pack(side=tkinter.RIGHT, fill=tkinter.Y)
    rcvlst = tkinter.Listbox(frame21, height=20, yscrollcommand=scrollbar4.set)
    scrollbar4.config(command=rcvlst.yview)
    rcvlst.pack(fill=tkinter.BOTH)
    rcvlst.bind("<Double-Button-1>", rcvlstdbclick)
    rcvlst.bind("<Button-3>", rcvlstrightclick)
    # 右键popmenu
    menu_pop = tkinter.Menu(rcvlst, tearoff=0)
    menu_pop.add_command(label="打开文件夹", command=rcvlst_opendir)
    frame21.pack(fill=tkinter.BOTH)

    # 目标用户信息
    frame22 = tkinter.Frame(frame2)
    sndvar = tkinter.StringVar()
    sndvar.set("未知目标")
    pil_img = Image.open(r"avatar\logout.jpg")
    pil_img = pil_img.resize((50, 50), Image.ANTIALIAS)
    tk_img = ImageTk.PhotoImage(pil_img)
    sndimg = tkinter.Label(frame22, image=tk_img, width=40, height=40)
    sndimg.pack(side=tkinter.LEFT)
    sndlbl = tkinter.Label(frame22, textvariable=sndvar, fg="red")
    sndlbl.pack(side=tkinter.LEFT)
    frame22.pack(fill=tkinter.BOTH)

    # 发送信息输入
    frame23 = tkinter.Frame(frame2)
    scrollbar5 = tkinter.Scrollbar(frame23)
    scrollbar5.pack(side=tkinter.RIGHT, fill=tkinter.Y)
    sndtext = tkinter.Text(frame23,
                           font=('微软雅黑', 10),
                           height=5,
                           yscrollcommand=scrollbar5.set)
    scrollbar5.config(command=sndtext.yview)
    sndtext.pack(side=tkinter.TOP, fill=tkinter.BOTH)
    # 允许拖放文件、绑定Drop事件
    if canDrop:
        sndtext.drop_target_register(DND_FILES, DND_TEXT)
        sndtext.dnd_bind('<<Drop>>', drop)
        # sndtext.bind(("<>"))
        sndtext.bind("<Control-KeyPress>", getkey)

    frame23.pack(fill=tkinter.BOTH)
    sndbtn = tkinter.Button(frame2,
                            text='发送',
                            width=15,
                            bg="green",
                            fg="white",
                            command=sndbtnclick)
    sndbtn.pack(side=tkinter.BOTTOM)
    sndbtn["state"] = tkinter.DISABLED
    frame2.pack(fill=tkinter.BOTH)
    # 底部
    frameb = tkinter.Frame(root)

    frameb.pack(side=tkinter.BOTTOM)

    # print(autologin)
    if autologin == 1:
        loginth()

    # 监听oa公告

    root.mainloop()
    # embed()
